const schedule = require('node-schedule');
//数据库模块
//1.导入mysql模块
const mysql = require('mysql')
    //2.建立与MySQL数据库的连接
const db = mysql.createPool({
    // host: '127.0.0.1',
    host: '10.0.224.12',
    user: 'david',
    password: 'David1234',
    database: 'hsdata',
    port: '3306'
})
const initSchedule=async()=>{
  var rule= new schedule.RecurrenceRule();
  rule.hour=13
  schedule.scheduleJob(rule,async ()=>{
    let day=getDateStrSimple()
    console.log(day,Date.now())
    db.query("select status from course WHERE status=0 and class_date=?",day,(err,res)=>{
      if(err) return console.log("错误了",err.message)
      console.log(getDateStrSimple() +" - 定时任务执行 : ",res)
      if(res.length>0){
        db.query('UPDATE course SET status=1 WHERE class_date=?',day, (err, results) => {
          if (err) return console.log(err.message) //失败
          console.log('定时课程发布成功!') //成功
      })
      }
    })
    
  });

}
function getDateStrSimple() {

  var oDate = new Date(Date.now()+2 * 24 * 60* 60 * 1000),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay);//最后拼接时间  
  return oTime;

};

function getzf(num) {
  if (parseInt(num) < 10) {
    num = '0' + num;
  }
  return num;
};
module.exports=initSchedule